//
//  SLMP4Parser+Dinf.m
//  SLVideoParser
//
//  Created by S_LINE on 2020/6/19.
//  Copyright © 2020 S_LINE. All rights reserved.
//

#import "SLMP4Parser+Dinf.h"

#import "SLParserUtil.h"

@implementation SLMP4Parser (Dinf)

- (NSDictionary *)drefParser:(NSData *)data
{
    if (data.length < 1)
    {
        return nil;
    }
    NSString *versionKey = @"version";
    NSString *flagsKey = @"flags";
    NSString *entryCountKey = @"entryCount";
    NSString *entryInfoKey = @"entryInfo";
    NSMutableDictionary *dict = [NSMutableDictionary new];
    NSData *versionData = [data subdataWithRange:NSMakeRange(0, 1)];
    uint64_t version = [SLParserUtil hexToDecimalWithData:versionData];
    [dict setObject:[NSNumber numberWithUnsignedLongLong:version] forKey:versionKey];
    uint64_t offset = 1;
    
    if (version == 0)
    {
        uint64_t flagsSize = 3;
        NSData *flagsData = [data subdataWithRange:NSMakeRange(offset, flagsSize)];
        uint64_t flags = [SLParserUtil hexToDecimalWithData:flagsData];
        offset += flagsSize;
        // entry count “url”或“urn”表的元素个数
        uint64_t entryCountSize = 4;
        NSData *entryCountData = [data subdataWithRange:NSMakeRange(offset, entryCountSize)];
        uint64_t entryCount = [SLParserUtil hexToDecimalWithData:entryCountData];
        offset += entryCountSize;
        // “url”或“urn”列表
        NSMutableArray *urlArray = [NSMutableArray new];
        for (int i = 0; i < entryCount; i++)
        {
            uint64_t sizeSize = 4;
            NSData *sizeData = [data subdataWithRange:NSMakeRange(offset, sizeSize)];
            uint64_t size = [SLParserUtil hexToDecimalWithData:sizeData];
            offset += sizeSize;
            
            uint64_t typeSize = 4;
            NSData *typeData = [data subdataWithRange:NSMakeRange(offset, typeSize)];
            NSString *type = [SLParserUtil hexToStringTypeWithData:typeData];
            offset += typeSize;
            
            uint64_t flagSize = 4;
            NSData *flagData = [data subdataWithRange:NSMakeRange(offset, flagSize)];
            uint64_t flag = [SLParserUtil hexToDecimalWithData:flagData];
            offset = offset + (size - typeSize - sizeSize);
            
            [urlArray addObject:[NSString stringWithFormat:@"size: %llu, type: %@, flag: %llu", size, type, flag]];
        }
        
        [dict setObject:[NSNumber numberWithUnsignedLongLong:flags] forKey:flagsKey];
        [dict setObject:[NSNumber numberWithUnsignedLongLong:entryCount] forKey:entryCountKey];
        [dict setObject:urlArray forKey:entryInfoKey];
    }
    
    return [dict copy];
}

@end
